package com.example.freeengine.filetranslate.fragment.send;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.freeengine.R;
import com.example.freeengine.databinding.FragmentFiletranslateSendBinding;
import com.example.freeengine.filetranslate.FileTranslateViewModel;
import com.example.freeengine.filetranslate.constants.FileTranslateConstant;
import com.example.freeengine.filetranslate.fragment.send.listadapter.FileTranslateDownloadListAdapter;
import com.example.freeengine.filetranslate.persistence.entity.FileTranslateDownloadFile;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.koushikdutta.async.http.server.AsyncHttpServer;
import com.koushikdutta.async.http.server.AsyncHttpServerRequest;
import com.koushikdutta.async.http.server.AsyncHttpServerResponse;
import com.koushikdutta.async.http.server.HttpServerRequestCallback;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import static android.app.Activity.RESULT_OK;

public class FiletranslateSendFragment extends Fragment {

    private static final String TAG = FiletranslateSendFragment.class.getSimpleName();
    private static final int REQUEST_FILE_SELECT = 1;
    FragmentFiletranslateSendBinding viewBinding;
    FileTranslateViewModel viewModel;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        viewBinding = FragmentFiletranslateSendBinding.inflate(inflater);
        return viewBinding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Toolbar toolbar = requireActivity().findViewById(R.id.tb_filetranslate);
        toolbar.setTitle("发送");
        viewModel = new ViewModelProvider(requireActivity()).get(FileTranslateViewModel.class);

        FileTranslateDownloadListAdapter fileTranslateDownloadListAdapter = new FileTranslateDownloadListAdapter(requireContext(), viewModel);
        viewBinding.rvFiletranslateSend.setLayoutManager(new LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false));
        viewBinding.rvFiletranslateSend.setAdapter(fileTranslateDownloadListAdapter);
        viewBinding.rvFiletranslateSend.addItemDecoration(new DividerItemDecoration(requireContext(), DividerItemDecoration.VERTICAL));
        viewModel.getFileTranslateRepository().findAllDownloadFiles().observe(requireActivity(), new Observer<List<FileTranslateDownloadFile>>() {
            @Override
            public void onChanged(List<FileTranslateDownloadFile> fileTranslateDownloadFiles) {
                fileTranslateDownloadListAdapter.submitList(fileTranslateDownloadFiles);
            }
        });

        // 添加本地文件
        viewBinding.btnFiletranslateSendFileAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                //intent.setType("image/*");//选择图片
                //intent.setType(“audio/*”); //选择音频
                //intent.setType(“video/*”); //选择视频 （mp4 3gp 是android支持的视频格式）
                //intent.setType(“video/*;image/*”);//同时选择视频和图片
                intent.setType("*/*");//无类型限制
                // intent.putExtra(EXTRA_ALLOW_MULTIPLE, true);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                startActivityForResult(intent, REQUEST_FILE_SELECT);
            }
        });

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_FILE_SELECT && resultCode == RESULT_OK && data != null){
            Uri fileUri;
            if (data.getData() != null){
                fileUri = data.getData();
                // 复制文件
                File dstDir = new File(requireContext().getFilesDir() + FileTranslateConstant.FILETRANSLATE_SEND_FILE_PATH);
                if (!dstDir.exists()) dstDir.mkdirs();

                String fileName = getFileDisplayName(requireContext(), fileUri);

                String fileRealName = System.currentTimeMillis() + "_" + fileName;

                File dstFile = new File(dstDir, fileRealName);
                if (!dstFile.exists()) {
                    try {
                        dstFile.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                byte[] fData = new byte[1024];
                int len, size = 0;
                try (InputStream inputStream = requireContext().getContentResolver().openInputStream(fileUri);
                     OutputStream os = new FileOutputStream(dstFile)){
                    while ((len = inputStream.read(fData)) > 0){
                        os.write(fData, 0, len);
                        size += len;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    dstFile.deleteOnExit();
                }

                try {
                    FileTranslateDownloadFile fileTranslateDownloadFile = new FileTranslateDownloadFile();
                    fileTranslateDownloadFile.setName(fileName);
                    fileTranslateDownloadFile.setSize(size);
                    fileTranslateDownloadFile.setFilePath(requireContext().getFilesDir() + FileTranslateConstant.FILETRANSLATE_SEND_FILE_PATH + fileRealName);

                    viewModel.getFileTranslateRepository().insert(fileTranslateDownloadFile);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static String getFileDisplayName(Context context, Uri uri) {
        Cursor cursor = null;
        String column = MediaStore.MediaColumns.DISPLAY_NAME;
        String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, null, null,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return "-";
    }

    @Override
    public void onStop() {
        super.onStop();
    }
}